//
//  baseRequest.swift
//  PerfectTemplate
//
//  Created by Master on 2017/1/17.
//
//

import Foundation

typealias successBlock = (Any) ->Void
typealias failureBlock = (NSError) ->Void

class baseRequest: NSObject ,NSURLConnectionDataDelegate {
    func getData(urlString:String,success:@escaping successBlock,failure:@escaping failureBlock){
        let msgData = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        let testData = msgData?.data(using: String.Encoding.utf8) // String转UTF8
        let UTF8String:String = (NSString(data: testData!, encoding: String.Encoding.utf8.rawValue))! as String // UTF8
        let url = URL(string: UTF8String)
        var request = URLRequest(url: url!)
        let list  = NSMutableArray()
        let paramDic = [String: String]()
        if paramDic.count > 0 {
            
            //设置为POST请求
            
            request.httpMethod = "GET"
            
            //拆分字典,subDic是其中一项，将key与value变成字符串
            
            for subDic in paramDic {
                
                let tmpStr = "\(subDic.0)=\(subDic.1)"
                
                list.add(tmpStr)
                
            }
            
            //用&拼接变成字符串的字典各项
            
            let paramStr = list.componentsJoined(by: "&")
            
            //UTF8转码，防止汉字符号引起的非法网址
            
            let paraData = paramStr.data(using: String.Encoding.utf8)
            
            //设置请求体
            
            request.httpBody = paraData
            
        }
        
        let configuration:URLSessionConfiguration = URLSessionConfiguration.default
        
        let session:URLSession = URLSession(configuration: configuration)
        
        let task:URLSessionDataTask = session.dataTask(with: request) { (data, response, error)->Void in

            if error == nil{
                
                do{
                    
                    let responseData:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary

                    success(responseData)
//                    print("返回数据:\(responseData)")
  
                }catch{
                    
                    print("catch")
                    
                }
                
            }else{
                
                print("error:\(error)")
                failure(error as! NSError)
                
            }
            
        }
        
        // 启动任务
        
        task.resume()
        
    }
    


}
